package com.log.resolver;

import com.log.resolver.interfaces.LogBody;
import com.log.utils.CommonUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @ClassName DefaultLogBody
 * @Author xiezhuocai
 * @Description TODO
 * @Date 2022/5/12 20:38
 */
public class DefaultLogBody implements LogBody {

    private String target;
    private char front;
    private char queen;

    public DefaultLogBody(String target){
        this.target = target;
        this.front = '{';
        this.queen = '}';
    }

    @Override
    public List<String> section(){
        return CommonUtils.section(target,front,queen);
    }

    @Override
    public String entirely(Map<String,String> logParam){
        AtomicReference<String> result = new AtomicReference<>(target);
        logParam.forEach((k,v)->{
            if (StringUtils.isEmpty(v)) v = "null";
            result.set(result.get().replace(fqKey(k), v));
        });
        List<String> key = CommonUtils.section(result.get(), front, queen);
        if (!key.isEmpty()) {
            for (String k : key) {
                result.set(result.get().replace(fqKey(k), "null"));
            }
        }
        return result.get();
    }

    public StringBuilder fqKey(String k){
        StringBuilder key = new StringBuilder();
        key.append(front);
        key.append(k);
        key.append(queen);
        return key;
    }
}
